package com.shanzhu.beadhouse.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shanzhu.beadhouse.common.util.PageUtil;
import com.shanzhu.beadhouse.dao.mapper.ServicePurchaseMapper;
import com.shanzhu.beadhouse.entity.base.PageResult;
import com.shanzhu.beadhouse.entity.base.Result;
import com.shanzhu.beadhouse.entity.po.ServicePurchase;
import com.shanzhu.beadhouse.entity.query.*;
import com.shanzhu.beadhouse.entity.vo.PageServiceLogVo;
import com.shanzhu.beadhouse.service.IServicePurchaseService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Service
public class ServicePurchaseServiceImpl implements IServicePurchaseService {
    @Resource
    private ServicePurchaseMapper servicePurchaseMapper;

    @Resource
    private PageUtil pageUtil;

    @Override
    public Result addPurchase(AddPurchaseFromListQuery query) {
        List<ServicePurchase> list = query.getPurchaseList();
        System.out.println(JSONUtil.toJsonStr(list));
        if (list==null||list.isEmpty()){
            return Result.success();
        }

        LocalDate now = LocalDate.now();
        // 获取3个月后的日期
        LocalDate threeMonthsLater = now.plusMonths(3);

        // 将 LocalDate 转换为 Date
        Date overdueDate = Date.from(threeMonthsLater.atStartOfDay(ZoneId.systemDefault()).toInstant());

        for (ServicePurchase servicePurchase : list) {
            servicePurchase.setOverdue(overdueDate); // 使用转换后的 Date 类型
            servicePurchaseMapper.insert(servicePurchase);
        }
        return Result.success();
    }

    @Override
    public Result pagePurchaseByKeys(PagePurchaseByKeysQuery query) {
        List<PageServiceLogVo> pageServiceLogVoList = servicePurchaseMapper.listPurchaseLogByKey(query);
        PageResult<PageServiceLogVo> pageResult = pageUtil.packPageResultData(pageServiceLogVoList,query.getPageNum(),query.getPageSize());
        return Result.success(pageResult);
    }


    @Override
    public Result getPurchase(GetPurchaseByIdQuery query) {

        return Result.success(servicePurchaseMapper.getPurchase(query));
    }

    @Override
    public Result resetHoldById(ResetHoldQuery query) {
        UpdateWrapper uw = new UpdateWrapper<>();
        uw.set("hold",query.getNum());
        uw.eq("id",query.getId());
        servicePurchaseMapper.update(null,uw);
        return Result.success();
    }

    @Override
    public Result deletePurchase(DeletePurchaseQuery query) {
        UpdateWrapper uw = new UpdateWrapper<>();
        uw.set("del_flag","Y");
        uw.eq("sid",query.getSid());
        uw.eq("eid",query.getEid());
        servicePurchaseMapper.update(null,uw);
        return Result.success();
    }
}
